﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Taobao.Tools2.Domain;
using System.Text.RegularExpressions;
using WeifenLuo.WinFormsUI.Docking;

namespace Taobao.Tools2
{
    public partial class RefreshSessionForm : DockContent//Form
    {
        #region Consts
        protected const string AuthorizeUrlKey = "authorizeUrl";
        protected const string ContainerUrlKey = "containerUrl";
        #endregion
        #region Ctor
        public RefreshSessionForm()
        {
            InitializeComponent();
            DbContext = new Domain.EntityFramework.EfDbContext();
            ShopRepository = new Taobao.Tools2.Domain.EntityFramework.EntityRepository<Shop>(DbContext);
        }
        #endregion

        #region Properties
        protected Taobao.Tools2.Domain.EntityFramework.EfDbContext DbContext { get; set; }
        protected IRepository<Shop> ShopRepository { get; set; }
        #endregion

        #region Events

        private void StartButton_Click(object sender, EventArgs e)
        {
            if (AllShopsComboBox.SelectedValue != null)
            {
                var selectedShop = (Shop)(AllShopsComboBox.SelectedValue);
                MainWebBrowser.Navigate(string.Format(System.Configuration.ConfigurationManager.AppSettings[AuthorizeUrlKey], selectedShop.AppKey));
                AllShopsComboBox.Enabled = false; 
            }
        }
        #endregion

        #region Load

        private void RefreshSessionForm_Load(object sender, EventArgs e)
        {
            AllShopsComboBox.Items.Clear();
            var allShop = ShopRepository.FindAll().ToList();
            AllShopsComboBox.DisplayMember = "Name";
            AllShopsComboBox.DataSource = allShop; 
        }
        #endregion

        private void GetSessionButton_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ContainerTextBox.Text))
            {
                MainWebBrowser.Navigate(string.Format(System.Configuration.ConfigurationManager.AppSettings[ContainerUrlKey], ContainerTextBox.Text.Trim()));
            }
        }

        private void MainWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var containerUrl = string.Format(System.Configuration.ConfigurationManager.AppSettings[ContainerUrlKey], string.Empty);
            if (e.Url.ToString().Contains(containerUrl))
            {
                var content = MainWebBrowser.Document.Body.InnerText;
                var sessionKey = GetSessionKey(content);
                if (!string.IsNullOrWhiteSpace(sessionKey) && AllShopsComboBox.SelectedValue!=null)
                {
                    var selectedShop = (Shop)(AllShopsComboBox.SelectedValue);
                    var shop = ShopRepository.FindAll().AsQueryable().Where(s => s.ID == selectedShop.ID).SingleOrDefault();
                    if (shop != null)
                    {
                        shop.SessionKey = sessionKey;
                        ShopRepository.Update(shop);
                        MessageBox.Show(string.Format("更新店铺{0}的SessionKey:{1}成功！", selectedShop.Name, sessionKey)); 
                        AllShopsComboBox.Enabled = true; 
                    }
                }
            }
        }

        private string GetSessionKey(string containerReturnValue)
        {
            var regex = new Regex("&top_session=([^&]*)&");
            var match = regex.Match(containerReturnValue);
            if (match.Success && match.Groups.Count > 0)
            {
                return match.Groups[1].Value;
            } 
            return string.Empty;
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            AllShopsComboBox.Enabled = true;
        }
    }
}
